package com.hall.items.repo;

import com.hall.items.aggr.MyPlayerWeaponPack;
import com.hall.items.dto.MyPlayerWeaponPackDTO;
import dml.game.weapon.repo.WeaponPackRepository;
import erp.mongodb.MongodbMutexes;
import erp.mongodb.MongodbStore;
import erp.repository.Repository;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

public class MyPlayerWeaponPackRepository extends Repository<MyPlayerWeaponPack, Long>
        implements WeaponPackRepository<MyPlayerWeaponPack, Long> {

    private MongoTemplate mongoTemplate;

    public MyPlayerWeaponPackRepository(MongoTemplate mongoTemplate) {
        super(new MyPlayerWeaponPackDTOProxyStore(new MongodbStore<>(mongoTemplate, MyPlayerWeaponPackDTO.class)),
                new MongodbMutexes<>(mongoTemplate, 30000L, MyPlayerWeaponPackDTO.class.getName()));
        this.mongoTemplate = mongoTemplate;
    }

    public MyPlayerWeaponPack queryCurrentWeaponPack(long playerId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(playerId)
                .and("currentPack").is(true));
        return ((MyPlayerWeaponPackDTO) mongoTemplate.findOne(query, MyPlayerWeaponPackDTO.class)).toEntity();
    }

    public Long findMaxId() {
        if (mongoTemplate == null) {
            return null;
        }
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC, "_id"));
        query.limit(1);
        MyPlayerWeaponPackDTO maxEtt = mongoTemplate.findOne(query, MyPlayerWeaponPackDTO.class);
        if (maxEtt == null) {
            return null;
        }
        return maxEtt.getId();
    }
}
